using UnityEngine;
using QFramework;
using UnityEngine.UI;

namespace ProjectIndieFarm
{
    public partial class UIChallenge : ViewController, IController
    {
        private IChallengeSystem mChallengeSystem;
        private void Start()
        {
            mChallengeSystem = this.GetSystem<IChallengeSystem>();
            ChallengeItemTemplate.Hide();


            UpdateView();
        }
        private void OnEnable()
        {
            ChallengeSystem.OnChallengeChanged.Register(() =>
            {
                UpdateView();
            }).UnRegisterWhenDisabled(gameObject);
        }
        private void OnDestroy()
        {
            mChallengeSystem = null;
        }
        private void UpdateView()
        {
            if (mChallengeSystem == null) return;
            LayoutRoot.DestroyChildren();
            Debug.Log("***updatechallenge");

            foreach (var activeChallenge in mChallengeSystem.ActiveChallenges)
            {
                ChallengeItemTemplate.InstantiateWithParent(LayoutRoot)
                    .Self(self =>
                    {
                        self.SetData(activeChallenge);
                        self.UpdateView();
                    }).Show();
            }
            foreach (var finishChallenge in mChallengeSystem.FinishChallenges)
            {
                ChallengeItemTemplate.InstantiateWithParent(LayoutRoot)
                    .Self(self =>
                    {
                        self.SetData(finishChallenge);
                        self.UpdateView();
                    }).Show();
            }
        }

        public IArchitecture GetArchitecture()
        {
            return Global.Interface;
        }
    }
}
